<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }
    .box {
      width: 200px;
      height: 200px;
      background-color: pink;
      position: fixed;
      top: 0;
      left: 0;
    }
  </style>
</head>
<body>
  <div class="box"></div>
</body>
</html>

<script>
const box = document.querySelector('.box');

const move = e => {
  box.style.left = e.clientX - offsetX + 'px';
  box.style.top = e.clientY - offsetY + 'px';
}

let offsetX = 0, offsetY = 0;

box.addEventListener('mousedown', e => {
  offsetX = e.offsetX;
  offsetY = e.offsetY;

  // mousedown 的时候，能 拖动
  document.addEventListener('mousemove', move);
});


box.addEventListener('mouseup', e => {
  // 鼠标抬起 让 box 不能 move
  document.removeEventListener('mousemove', move);
});
</script>